package com.savi.myapplication.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.github.gcacace.signaturepad.views.SignaturePad;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfFormField;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.savi.myapplication.FlyCardActivity;
import com.savi.myapplication.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RecordCardFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RecordCardFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    static String pdfFilePath = null;
    private FlyCardActivity flyCardActivity ;
    private EditText record_line1_1;
    private EditText record_line1_2;
    private EditText record_line1_3;
    private EditText record_line2_1;
    private EditText record_line2_2;
    private EditText record_line2_3;
    private EditText record_comment;
    private CheckBox checkbox_option_1;
    private CheckBox checkbox_option_2;
    private CheckBox checkbox_option_3;
    private CheckBox checkbox_option_4;
    private CheckBox checkbox_option_5;
    private CheckBox checkbox_option_6;
    private CheckBox checkbox_option_7;
    private Button record_sign_1;
    private Button record_sign_2;
    private Button buttonGeneratePDF;
    private Bitmap signatureBitmap1;
    private Bitmap signatureBitmap2;
    public RecordCardFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RecordCardFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RecordCardFragment newInstance(String param1, String param2) {
        RecordCardFragment fragment = new RecordCardFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        flyCardActivity =  (FlyCardActivity) FlyCardActivity.getActivity();
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_record_card, container, false);

        record_line1_1 = view.findViewById(R.id.record_line1_1);
        record_line1_2 = view.findViewById(R.id.record_line1_2);
        record_line1_3 = view.findViewById(R.id.record_line1_3);
        record_line2_1 = view.findViewById(R.id.record_line2_1);
        record_line2_2 = view.findViewById(R.id.record_line2_2);
        record_line2_3 = view.findViewById(R.id.record_line2_3);
        record_comment = view.findViewById(R.id.record_comment);
        record_sign_1 = view.findViewById(R.id.record_sign_1);
        record_sign_2 = view.findViewById(R.id.record_sign_2);
        checkbox_option_1 = view.findViewById(R.id.checkbox_option_1);
        checkbox_option_2 = view.findViewById(R.id.checkbox_option_2);
        checkbox_option_3 = view.findViewById(R.id.checkbox_option_3);
        checkbox_option_4 = view.findViewById(R.id.checkbox_option_4);
        checkbox_option_5 = view.findViewById(R.id.checkbox_option_5);
        checkbox_option_6 = view.findViewById(R.id.checkbox_option_6);
        checkbox_option_7 = view.findViewById(R.id.checkbox_option_7);
        buttonGeneratePDF = view.findViewById(R.id.buttonGeneratePDF);
        buttonGeneratePDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    // 传入Fragment的context
                    generateTempPDF(getContext());
                    Toast.makeText(getContext(), "PDF生成成功！", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });

        record_sign_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LayoutInflater inflater = getLayoutInflater();
                View signatureView = inflater.inflate(R.layout.layout_signature_pad, null);
                final SignaturePad signaturePad = signatureView.findViewById(R.id.signaturePad);

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setView(signatureView)
                        .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 获取签名位图并保存到变量中
                                signatureBitmap1 = signaturePad.getSignatureBitmap();
                                // 将签名位图存储到本地
//                                saveSignatureToLocal(signatureBitmap1);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });

                // 创建 AlertDialog 对象
                final AlertDialog dialog = builder.create();

                // 在弹窗显示后调整大小
                dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialogInterface) {
                        // 获取对话框窗口
                        Window window = dialog.getWindow();
                        if (window != null) {
                            // 获取窗口布局参数
                            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
                            layoutParams.copyFrom(window.getAttributes());

                            // 设置弹窗宽度和高度（以像素为单位）
                            layoutParams.width = 1800;  // 宽度
                            layoutParams.height = 1000; // 高度

                            // 应用新的布局参数
                            window.setAttributes(layoutParams);
                        }
                    }
                });

                // 显示对话框
                dialog.show();
            }
        });
        record_sign_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LayoutInflater inflater = getLayoutInflater();
                View signatureView = inflater.inflate(R.layout.layout_signature_pad, null);
                final SignaturePad signaturePad = signatureView.findViewById(R.id.signaturePad);

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setView(signatureView)
                        .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 获取签名位图并保存到变量中
                                signatureBitmap2 = signaturePad.getSignatureBitmap();
                                // 将签名位图存储到本地
//                                saveSignatureToLocal(signatureBitmap2);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });

                // 创建 AlertDialog 对象
                final AlertDialog dialog = builder.create();

                // 在弹窗显示后调整大小
                dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialogInterface) {
                        // 获取对话框窗口
                        Window window = dialog.getWindow();
                        if (window != null) {
                            // 获取窗口布局参数
                            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
                            layoutParams.copyFrom(window.getAttributes());

                            // 设置弹窗宽度和高度（以像素为单位）
                            layoutParams.width = 1800;  // 宽度
                            layoutParams.height = 1000; // 高度

                            // 应用新的布局参数
                            window.setAttributes(layoutParams);
                        }
                    }
                });

                // 显示对话框
                dialog.show();
            }
        });

        // 初始化预览按钮
        Button buttonPreviewPDF = view.findViewById(R.id.buttonPreviewPDF);
        buttonPreviewPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用预览PDF的方法
                previewPDF(getContext(),pdfFilePath);
            }
        });
        return view;
    }

    // 修改generateTempPDF方法签名，传入Context
    public String generateTempPDF(Context context) throws Exception {
        PdfReader reader = null;
        PdfStamper ps = null;
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        InputStream is = null;
        try {
            // 获取外部存储的根目录
            File externalStorage = Environment.getExternalStorageDirectory();

            // 构建具体的文件路径
            File file = new File(externalStorage, "MFBdata/Template/RecordCardTemplatePDF.pdf");

            // 检查文件是否存在
            if (file.exists()) {
                // 如果文件存在，使用 FileInputStream 读取文件
                is = new FileInputStream(file);
                Log.d("FileSuccess", "模板文件已找到: " + file.getAbsolutePath());
            } else {
                // 如果文件不存在，提示未发现模板文件
                Log.e("FileError", "未发现模板文件: " + file.getAbsolutePath());
                Toast.makeText(context, "未发现模板文件", Toast.LENGTH_SHORT).show();
            }

            reader = new PdfReader(is);
            bos = new ByteArrayOutputStream();
            ps = new PdfStamper(reader, bos);

            // 使用中文字体
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<>();
            fontList.add(bf);

            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            for (String fieldName : fields.getFields().keySet()) {
                fields.setFieldProperty(fieldName, "textfont", bf, null);  // 设置中文字体
                fields.setFieldProperty(fieldName, "textsize", 12f, null);  // 设置字体大小为12
            }

            fillData(fields, getData(flyCardActivity)); // 渲染数据

            ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
            signatureBitmap1.compress(Bitmap.CompressFormat.PNG, 100, stream1);
            Image signatureImage1 = Image.getInstance(stream1.toByteArray());
            Rectangle signRect1 = fields.getFieldPositions("record_sign_1").get(0).position;

            float x1 = signRect1.getLeft();
            float y1 = signRect1.getBottom();

            float width1 = signRect1.getWidth();
            float height1 = signRect1.getHeight();

            // 调整图像大小
            signatureImage1.scaleToFit(width1-1, height1+10);
            signatureImage1.setAbsolutePosition(x1, y1 + 5);

            // 在PDF中添加图像
            ps.getOverContent(2).addImage(signatureImage1);

            ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
            signatureBitmap2.compress(Bitmap.CompressFormat.PNG, 100, stream2);
            Image signatureImage2 = Image.getInstance(stream2.toByteArray());
            Rectangle signRect2 = fields.getFieldPositions("record_sign_2").get(0).position;

            float x2 = signRect2.getLeft();
            float y2 = signRect2.getBottom();

            float width2 = signRect2.getWidth();
            float height2 = signRect2.getHeight();

            // 调整图像大小
            signatureImage2.scaleToFit(width2-1, height2+10);
            signatureImage2.setAbsolutePosition(x2, y2 + 5);

            // 在PDF中添加图像
            ps.getOverContent(2).addImage(signatureImage2);

            // 必须调用这个，否则文档不会生成
            ps.setFormFlattening(true);
            ps.close();

            // 获取当前日期作为文件夹名称
            String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

            // 获取当前时间戳作为文件名
            String timeStamp = String.valueOf(System.currentTimeMillis());

            // 构建你要保存的目录路径 /storage/F7A4-73C4/MFBdata/FlyCard
            File dir = new File(externalStorage, "MFBdata/RecordCard");
            // 创建文件夹路径

            if (!dir.exists()) {
                dir.mkdirs();  // 创建日期文件夹
            }

            // 生成 PDF 文件的路径
            pdfFilePath = dir.getAbsolutePath() + "/" + timeStamp + ".pdf";

            // 写入 PDF 文件
            fos = new FileOutputStream(pdfFilePath);
            fos.write(bos.toByteArray());

            Log.d("PDFGeneration", "PDF 生成成功: " + pdfFilePath);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (reader != null) {
                reader.close();
            }
            if (is != null) {
                is.close();
            }
        }

        return pdfFilePath;  // 返回生成的 PDF 文件路径
    }

    /**
     * 填充模板中的数据
     */
    public static void fillData(AcroFields fields, Map<String, String> data) {
        try {
            for (String key : data.keySet()) {
                String value = data.get(key);
                // 为字段赋值,注意字段名称是区分大小写的
                fields.setField(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Map<String, String> getData(Activity activity) {
        Map<String, String> data = new HashMap<>();
        data.put("record_line1_1", record_line1_1.getText().toString());
        data.put("record_line1_2", record_line1_2.getText().toString());
        data.put("record_line1_3", record_line1_3.getText().toString());
        data.put("record_line2_1", record_line2_1.getText().toString());
        data.put("record_line2_2", record_line2_2.getText().toString());
        data.put("record_line2_3", record_line2_3.getText().toString());
        data.put("record_comment", record_comment.getText().toString());
        data.put("record_sign_1", record_sign_1.getText().toString());
        data.put("record_sign_2", record_sign_2.getText().toString());

        data.put("checkbox_option_1", checkbox_option_1.isChecked() ? "√" :"");
        data.put("checkbox_option_2", checkbox_option_2.isChecked() ? "√" :"");
        data.put("checkbox_option_3", checkbox_option_3.isChecked() ? "√" :"");
        data.put("checkbox_option_4", checkbox_option_4.isChecked() ? "√" :"");
        data.put("checkbox_option_5", checkbox_option_5.isChecked() ? "√" :"");
        data.put("checkbox_option_6", checkbox_option_6.isChecked() ? "√" :"");
        data.put("checkbox_option_7", checkbox_option_7.isChecked() ? "√" :"");
        for (int i = 1; i <= 21; i++) {
            for(int j=1;j<=6;j++){
                String viewIdName = "record_list" + i+"_"+j;
                int resId = activity.getResources().getIdentifier(viewIdName, "id", activity.getPackageName());
                EditText editText = activity.findViewById(resId);
                if (editText != null) {
                    String value = editText.getText().toString();
                    data.put(viewIdName, value);
                }
            }
        }
        return data;
    }

    // 添加预览PDF的方法
    public void previewPDF(Context context, String pdfFilePath) {
        File pdfFile = new File(pdfFilePath);  // 传入最新生成的文件路径
        if (pdfFile.exists()) {
            Uri pdfUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", pdfFile);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(pdfUri, "application/pdf");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {
                context.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(context, "没有找到可以打开 PDF 的应用", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "PDF 文件不存在，请先生成 PDF", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveSignatureToLocal(Bitmap signatureBitmap) {
        FileOutputStream outputStream = null;
        try {
            // 创建文件名和路径
            File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Signatures");
            if (!directory.exists()) {
                directory.mkdirs(); // 创建存储目录
            }
            String fileName = "signature_" + System.currentTimeMillis() + ".png";
            File signatureFile = new File(directory, fileName);

            // 打开文件输出流
            outputStream = new FileOutputStream(signatureFile);

            // 将位图压缩为PNG并写入文件
            signatureBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);

            // 刷新文件输出流，确保所有数据被写入
            outputStream.flush();

            // 提示用户保存成功
            Toast.makeText(this.getContext(), "签名已保存至: " + signatureFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this.getContext(), "保存签名失败", Toast.LENGTH_LONG).show();
        } finally {
            // 关闭输出流
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}